package com.explorati.design_pattern.comparson.structural.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

import com.explorati.design_pattern.comparson.structural.proxy.IStar;
import com.explorati.design_pattern.comparson.structural.proxy.Star;

public class DynamicProxy implements InvocationHandler {

	private Object target;

	public DynamicProxy(Object target) {
		this.target = target;
	}

	public Object bind() {
		Class cls = target.getClass();
		return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object obj = null;
		if ("action".equals(method.getName())) {
			boolean flag = canAction();
			if (flag) {
				System.out.println(this.showName(target) + "档期已满，无法拍戏");
				obj = method.invoke(target, args);
			} else {

			}
		} else {
			obj = method.invoke(target, args);
		}
		return obj;
	}

	private boolean canAction() {
		Random rand = new Random();
		int i = rand.nextInt(10);
		return i < 5 ? true : false;
	}

	private String showName(Object obj) {
		obj = target;
		if (obj instanceof Star) {
			return ((Star) obj).getName();
		}
		return null;
	}

}
